package vn.com.vega.chacha.v2.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkStatusReceiver extends BroadcastReceiver {

	public static final int CONNECTION_TYPE_OFF = 0;
	public static final int CONNECTION_TYPE_WIFI = 1;
	public static final int CONNECTION_TYPE_3G = 2;

	public static final String NETWORK_CHANGE = "vn.com.vega.chacha.networkchange";
	public static final String NETWORK_OFF = "vn.com.vega.chacha.networkoff";

	public static int networkStatus;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		networkStatus = getNetworkStatus(context);
		Intent inten = new Intent();
		if (networkStatus == CONNECTION_TYPE_OFF) {
			inten.setAction(NETWORK_OFF);
		} else {
			inten.setAction(NETWORK_CHANGE);
		}
		context.sendStickyBroadcast(inten);
		// LocalBroadcastManager.getInstance(context).sendBroadcast(inten);
	}

	public static boolean isConnected() {
		return networkStatus != CONNECTION_TYPE_OFF;
	}

	public static int getNetworkStatus(Context ctx) {
		ConnectivityManager connec = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo currentNetworkInfo = connec.getActiveNetworkInfo();

		if (currentNetworkInfo == null) {
			return CONNECTION_TYPE_OFF;
		}

		if (currentNetworkInfo.isConnected()) {
			if (currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				return CONNECTION_TYPE_WIFI;
			} else {
				return CONNECTION_TYPE_3G;
			}
		} else {
			return CONNECTION_TYPE_OFF;
		}

	}

}
